<template>
  <van-sticky>
    <Header title="排课情况"/>
  </van-sticky>
  <div class="content">
    <div class="search">
      <!--校区--> <!--  周次-->
      <van-cell-group>
        <van-row class="row">
          <!--校区-->
          <van-col span="13">
            <van-field
                v-model="campus"
                readonly
                name="campus"

                placeholder="选择校区"
                @click="click1"
            >
              <template #left-icon>
                <van-icon name="wap-home" />
<!--                <nut-icon name="Locationg3"></nut-icon>-->
              </template>
              <template #button>
                <van-icon name="arrow-down"/>
              </template>
            </van-field>
          </van-col>
          <!--  周次-->
          <van-col span="11">
            <van-field
                v-model="theWeek"
                readonly
                name="week"

                placeholder="选择周次"
                @click="click2"
            >
              <template #left-icon>
<!--                <van-icon name="success"/>-->
<!--                <van-icon name="star" />-->
                <van-icon name="clock" />
              </template>
              <template #button>
                <van-icon name="arrow-down"/>
              </template>
            </van-field>
          </van-col>
        </van-row>
      </van-cell-group>
      <!--星期--> <!--  节次-->
      <van-cell-group>
        <van-row class="row">
          <!--星期-->
          <van-col span="12">
            <van-field
                v-model="day"
                readonly
                name="day"

                placeholder="选择星期"
                @click="click3"
            >
              <template #left-icon>
                <van-icon name="info" />
              </template>
              <template #button>
                <van-icon name="arrow-down"/>
              </template>
            </van-field>
          </van-col>
          <!--  节次-->
          <van-col span="11">
            <van-field
                v-model="part"
                readonly
                name="part"

                placeholder="选择节次"
                @click="click4"
            >
              <template #left-icon>
                <van-icon name="star" />
              </template>
              <template #button>
                <van-icon name="arrow-down"/>
              </template>
            </van-field>
          </van-col>
        </van-row>
      </van-cell-group>
    </div>
    <!--  详细信息-->
    <div class="list">
      <nut-collapse icon="down-arrow" v-model:active="activeName" accordion>
        <nut-collapse-item v-for="(item, index) in data.newRoomList" :title="item.building" :name="index">
          <div class="classRoomItem" v-for="(r, i) in item.classRoom" :key="i">
            <van-row justify="space-between" style="margin-bottom: 2vh">
              <van-col spam="1"><span style="border: 0.5vw solid #1989fa;"></span></van-col>
              <van-col span="21" style="font-size: 4vw; color: #666666"> {{ r.coursrName }}</van-col>
              <van-col span="2">
                <van-icon size="4.5vw" @click="changeRoomDialog(r)" name="ellipsis"/>
              </van-col>
            </van-row>
            <van-row class="row">
              <van-col span="10" offset="1">{{ r.roomName }}</van-col>
              <van-col span="8">{{ r.teacherName }}</van-col>
              <van-col span="4" offset="1"><van-button @click="tkMessage(r)" class="tkbutton">听课</van-button></van-col>
            </van-row>
          </div>
        </nut-collapse-item>
      </nut-collapse>
      <van-empty v-if="data.newRoomList == null" image-size="15rem" description="无上课教室"/>
      <VanPopup overlay="false" v-model:show="popupVisible" round position="center" :style="{ width: '80%'}">
        <div style="padding: 5vw;">
          <h4>详细信息</h4>
          <div class="cell-container">
            <div class="cell-title">教室</div>
            <div style="color: #8f8f94">
              {{ dialogData.roomName }}
            </div>
          </div>

          <div class="cell-container">
            <div class="cell-title">教师</div>
            <div style="color: #8f8f94">
              {{ dialogData.teacherName }}
            </div>
          </div>

          <div class="cell-container">
            <div>课程</div>
            <div style="color: #8f8f94">
              {{ dialogData.coursrName }}
            </div>
          </div>

          <div class="cell-container">
            <div>周次</div>
            <div style="color: #8f8f94">
              {{ dialogData.weekName }}
            </div>
          </div>

          <div class="cell-container">
            <div>班级</div>
            <div style="color: #8f8f94">
              <van-row justify="end" gutter="10" :wrap="false">
                <van-col v-for="(item, index) in dialogData.classes" :key="index">
                  {{ item.class }}
                </van-col>
              </van-row>
            </div>
          </div>
        </div>

        <div style="text-align: center; color: orangered; padding:2vw 0 3vw 0;border-top: 1px solid rgba(154,155,157,0.27)" @click="hidePopup">
          <span style="text-align: center; font-weight: 400;">确认</span>
        </div>
      </VanPopup>
      <van-popup v-model:show="tkShow" round position="center" :style="{ width: '80%', height:'auto' }">
        <div style="padding: 5vw;">
          <h4>是否进行听课</h4>

          <div class="cell-container">
            <div>课程</div>
            <spqn style="color: #8f8f94">{{tkData.coursrName}}</spqn>
          </div>

          <div class="cell-container">
            <div>教师</div>
            <div style="color: #8f8f94;width: 50%;height: 25px">
              <van-dropdown-menu :overlay="false" style="width: 100%; top:90px;" >
                <van-dropdown-item  v-model="teacherID" :options="tName" style="color: #8f8f94;" />
              </van-dropdown-menu>
            </div>

          </div>

          <div class="cell-container">
            <div>角色</div>
<!--            <van-dropdown-menu :overlay="false" style="width: 50%;">-->
<!--              <van-dropdown-item v-model="value1" :options="option1" style="color: #8f8f94;" class="item"/>-->
<!--            </van-dropdown-menu>-->
          </div>
        </div>

        <div style="display: flex;  border-top: 1px solid rgba(154,155,157,0.27); height: 10vw;" @click="hideTk">
          <van-button style="font-weight: 400; width: 50%; height: 10vw; text-align: center; color: rgb(70,66,66); ">取消</van-button>
          <van-button style="font-weight: 400; width: 50%; height: 10vw; text-align: center; color: #2b95ef;" @click="tkAdd">确认</van-button>
        </div>
      </van-popup>

      <van-dropdown-menu :overlay="false" style="width: 50%;" v-if="tkShow" z-index="99999">
        <van-dropdown-item v-model="value1" :options="option1" style="color: #8f8f94;" class="item"/>
      </van-dropdown-menu>
    </div>
  </div>
  <div class="blank"></div>
  <!--校区-->
  <van-popup round v-model:show="showCampusPicker" position="bottom">
    <van-picker
        title="选择校区"
        :columns="data.rooms"
        :default-index="(selectParams.zoomId-1)"
        @confirm="onConfirmCampus"
        @cancel="showCampusPicker = false"
    />
  </van-popup>
  <!--  周次-->
  <van-popup round v-model:show="showWeekPicker" position="bottom">
    <van-picker
        title="选择周次"
        :round="true"
        :columns="data.zcs"
        :default-index="(selectParams.zc-1)"

        @confirm="onConfirmWeek"
        @cancel="showWeekPicker = false"

    />
  </van-popup>
  <!--星期-->
  <van-popup round v-model:show="showDayPicker" position="bottom">
    <van-picker
        title="选择星期"
        :columns="data.weeks"
        :default-index="(selectParams.week-1)"

        @confirm="onConfirmDay"
        @cancel="showDayPicker = false"

    />
  </van-popup>
  <!--  节次-->
  <van-popup round v-model:show="showPartPicker" position="bottom">
    <van-picker
        title="选择节次"
        :round="true"
        :columns="data.sections"
        :default-index="(selectParams.section-1)"

        @confirm="onConfirmPart"
        @cancel="showPartPicker = false"

    />
  </van-popup>
</template>

<script setup>
import Header from "/@/components/Header/Header.vue";
import {getClassInfo, getZoomIds} from "/@/api/hbmy_wx/skqk";
import {Dialog, Toast} from "vant";
import 'vant/lib/index.css'
import {addTkRecordUrl, getViceTeacher} from "../../api/new_module/listen_class/tkTable";
import * as json from "postcss";
import {useRouter} from "vue-router/dist/vue-router";

const tName = ref([])
let tkData = reactive({})
const tkShow = ref(false)
const teacherID = ref("")
const tcID = ref("")
const section = ref("")
const router = useRouter();
const value1 = ref(0)
const option1 = [
  { text: '全部商品', value: 0 },
  { text: '新款商品', value: 1 },
  { text: '活动商品', value: 2 }
]


const tkMessage = async (value) =>{
  teacherID.value = value.teacherID
  tcID.value = value.tcID
  section.value = value.section
  const data = await getViceTeacher(value.tcID,"theory")
  console.log('data', data.response)
  if(tName.value.length > 0)
  {
    tName.value = [];
  }
  if(data.response.value.data.length > 0)
  {
    for(let i = 0; i < data.response.value.data.length; i++)
    {
      tName.value.push({text: data.response.value.data[i].name, value:data.response.value.data[i].id})
    }
  }else {
    tName.value.push({text: value.teacherName, value: value.teacherID})
  }
  console.log('tName', tName.value)
  // 属性赋值，保证响应试
  tkData.coursrName = value.coursrName;
  console.log('tkData', tkData.coursrName)
  setTimeout(() => {
    tkShow.value = true;
  }, 150);
}

const hideTk = () =>{
  tkShow.value = false
}

//校区
const campus = ref()
const showCampusPicker = ref(false)

const onConfirmCampus = (value, index) => {
  campus.value = value
  selectParams.zoomId = getiID(data.rooms[index])
  console.log("111111111111111111111selectParams.zoomId", selectParams.zoomId)
  showCampusPicker.value = false
}
//周次
const theWeek = ref()
const showWeekPicker = ref(false)
const onConfirmWeek = (value, index) => {
  theWeek.value = value
  console.log("111111111111111111111selectParams.zc", index + 1)
  selectParams.zc = index + 1
  showWeekPicker.value = false
}

//星期
const day = ref()
const showDayPicker = ref(false)
const onConfirmDay = (value, index) => {
  day.value = value
  console.log("111111111111111111111selectParams.week", index + 1)
  selectParams.week = index + 1
  showDayPicker.value = false
}
//节次
const part = ref()
const showPartPicker = ref(false)
const onConfirmPart = (value, index) => {
  part.value = value
  console.log("111111111111111111111selectParams.section", index + 1)
  selectParams.section = index + 1
  showPartPicker.value = false
}
const click1 = () => {
  showCampusPicker.value = true
  open()
}
const click2 = () => {
  showWeekPicker.value = true
  open()
}
const click3 = () => {
  showDayPicker.value = true
  open()
}
const click4 = () => {
  showPartPicker.value = true
  open()
}
// const activeNames = reactive([]);
const activeName = ref(-1);

let dialogData = reactive({})
const popupVisible = ref(false);

const hidePopup = () => {
  popupVisible.value = false;
};


const data = reactive({
  rooms: [],
  zcs: [],
  weeks: [
    '周一',
    '周二',
    '周三',
    '周四',
    '周五',
    '周六',
    '周日',
  ],
  sections: [],
  roomList: [],

  // 重构后roomList
  newRoomList: [],
  firstTime: null,
})

let selectParams = reactive({
  zoomId: -1,
  zc: -1,
  week: -1,
  section: -1
})
const open = () => {
  console.log("open")
  activeName.value = -1
}

const object = JSON.parse(localStorage.getItem('USERINFO'));
data.firstTime = object.first;
let resRooms

async function initData() {
  await getZoomIds().then((res) => {
    resRooms = res.response.value.extend.zones
    console.log("resROOMS", res.response.value.extend.zones)
    resRooms.forEach((item) => {
      data.rooms.push(
          item.name
      );
    });
    console.log("rooms", data.rooms)
    campus.value = data.rooms[selectParams.zoomId - 1]
  }).catch((err) => {
    console.log(err);
  });
}

const getiID = (room) => {
  for (let resRoomsKey in resRooms) {
    if (resRooms[resRoomsKey].name === room) {
      return resRooms[resRoomsKey].iID
    }
  }
}

//教室详情
function changeRoomDialog(value) {
  // 属性赋值，保证响应试
  dialogData.classes = value.classes;
  dialogData.coursrName = value.coursrName;
  dialogData.roomName = value.roomName;
  dialogData.teacherName = value.teacherName;
  dialogData.weekName = value.weekName;
  console.log('dialogData', dialogData)
  setTimeout(() => {
    popupVisible.value = true;
  }, 150);
}

function initSelectParams() {

  for (let i = 0; i < 20; i++) {
    data.zcs.push(
        `第 ${i + 1} 周`
    );
  }
  for (let j = 1; j <= 10; j++) {
    data.sections.push(
        `第 ${j} 节`
    );
  }
  selectParams.zoomId = 1;
  let time = new Date().valueOf() - data.firstTime;
  let week = time / 1000 / 60 / 60 / 24 / 7 + 1;
  selectParams.zc = Math.floor(week) > 20 ? 1 : Math.floor(week);
  theWeek.value = data.zcs[selectParams.zc - 1]

  let weekDay = new Date().getDay();
  if (weekDay > 0) {
    console.log("weekDay", weekDay)
    selectParams.week = weekDay;
  } else {
    console.log("weekDay", weekDay + 7)
    selectParams.week = weekDay + 7;
  }
  day.value = data.weeks[selectParams.week - 1]
  let currentTime = new Date();
  let hours = currentTime.getHours();
  if (hours < 8) {
    selectParams.section = 1;
  } else if (hours < 9) {
    selectParams.section = 2;
  } else if (hours < 10) {
    selectParams.section = 3;
  } else if (hours < 11) {
    selectParams.section = 4;
  } else if (hours < 14) {
    selectParams.section = 5;
  } else if (hours < 15) {
    selectParams.section = 6;
  } else if (hours < 16) {
    selectParams.section = 7;
  } else if (hours < 17) {
    selectParams.section = 8;
  } else if (hours < 19) {
    selectParams.section = 9;
  } else if (hours < 20) {
    selectParams.section = 10;
  } else {
    selectParams.section = 10;
  }
  part.value = data.sections[selectParams.section - 1]
  console.log('selectParams', selectParams);
}

watch(
    () => selectParams.zc,
    () => {
      changeSelect()
    }
)
watch(
    () => selectParams.week,
    () => {
      changeSelect()
    }
)
watch(
    () => selectParams.section,
    () => {
      changeSelect()
    }
)
watch(
    () => selectParams.zoomId,
    () => {
      changeSelect()
    }
)

async function changeSelect() {
  console.log("selectParams.zc", selectParams.zc)
  console.log("selectParams.week", selectParams.week)
  console.log("selectParams.section", selectParams.section)
  console.log("selectParams.zoomId", selectParams.zoomId)
  await getClassInfo(
      selectParams.zc,
      selectParams.week,
      selectParams.section,
      selectParams.zoomId
  ).then((res) => {
    data.newRoomList = [];
    data.roomList = res.response.value.extend.rooms;
    if (!data.roomList) Toast("期间无上课教室")
    //TODO 同类项归并
    data.newRoomList = data.roomList?.reduce((result, current) => {
      const existingBuilding = result.find(item => item.building === current.building);

      if (existingBuilding) {
        existingBuilding.classRoom.push({
          classes: current.classes?.map(item => ({class: item})),
          coursrName: current.coursrName,
          persons: current.persons,
          roomID: current.roomID,
          roomName: current.roomName,
          tcID: current.tcID,
          teacherID: current.teacherID,
          teacherName: current.teacherName,
          weekName: current.weekName,
          zone: current.zone
        });
      } else {
        result.push({
          building: current.building,
          classRoom: [{
            classes: current.classes?.map(item => ({class: item})),
            coursrName: current.coursrName,
            persons: current.persons,
            roomID: current.roomID,
            roomName: current.roomName,
            tcID: current.tcID,
            teacherID: current.teacherID,
            teacherName: current.teacherName,
            weekName: current.weekName,
            zone: current.zone
          }]
        });
      }
      return result;
    }, []);

    console.log("newDataRooms", data.newRoomList);
  })
}


const tkAdd = async () =>{
  const base = Math.ceil(selectParams.section / 2);
  section.value = `${2*base-1}-${2*base}`;
  console.log("section", section.value)
  await addTkRecordUrl({
    teacherId: teacherID.value,
    tcId: tcID.value,
    section: section.value || '无'
  }).then((res) =>{
    Toast(res.data.msg)
    const tkId = res.data.tkId;
    if(tkId)
    {
      router.push({name: '听课问卷', query: {tkId: tkId}})
    }

  })

}


onMounted(() => {
  initData();

  initSelectParams();

  changeSelect();

})

</script>


<style scoped lang="less">
.tkbutton{
  background-color: rgba(43, 149, 239, 0.99);
  color: #f6f6f7;
  width: 15vw;
  height: 50px;
  border-radius: 10px;
  padding: 0;
}
.content .row[data-v-b7d08c3d] {
  color: #8f8f94;
  align-items: center;
}
/deep/.van-dropdown-menu .van-haptics-feedback {
  cursor: pointer;
  height: 50px;
}
/deep/.van-dropdown-menu__bar {
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  /* height: var(--van-dropdown-menu-height); */
  background: var(--van-dropdown-menu-background-color);
  box-shadow: var(--van-dropdown-menu-box-shadow);
  height: 50px;
}
.van-dropdown-item{
  top: 220px !important;
  width: 45%;
  margin-left: 50%;
  height: auto;
}
.item{
  top: 290px !important;
  height: auto;
}
/deep/.van-dropdown-menu__title--active {
  color: #2b95ef;
}
/deep/.van-dropdown-item__option--active, .van-dropdown-item__option--active .van-dropdown-item__icon {
  color: #2b95ef;
}
/deep/.van-ellipsis {
  color: #9a9b9d;
}
/deep/.van-dropdown-item__option {
  z-index: 99999 ;
  text-align: center;
  background-color: #f1f1f6;
  color: #9a9b9d;
  //border-color: #9a9b9d;
  .van-cell__value {
    display: none;
    width: 0;
  }
  .van-cell__title {
    margin: 0;
  }
  .van-overlay{
    display: none;
  }


}

.content {
  .search {
    padding: 1vh 2vw 0 2vw;
  }

  .row {
    color: #8f8f94;
  }

  .list {
    margin: 1vh 2vw;

    .classRoom {
      display: flex;
      flex-wrap: wrap;
    }

    .p {
      color: black;
    }

    .classRoomItem {
      padding: 2vw;

    }
  }
}

.cell-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #9a9b9d;
  font-weight: 400;
  margin-top: 20px;
}

h4 {
  color: #666666;
  text-align: center;
  font-weight: 400;
}

/deep/ .van-cell__title {
  margin-left: 3vw;
}

/deep/ .collapse-icon-title {
  color: #6d6d6d;
  font-size: 4.5vw;
}

/deep/ .nut-collapse-item .collapse-item {
  padding: 2vw 0 2vw 8vw;
  margin-top: 2vw;

}

/deep/ .nut-collapse-item .collapse-item .collapse-icon {
  color: #9a9b9d;

}

/deep/ .van-field__label {
  width: 8vw;
  color: #9a9b9d;
}

/deep/ .van-field__control {
  color: #2b95ef;
  text-align: center;
}

.blank {
  width: 100%;
  height: 5vh;
}

.van-icon{
  color: #9a9b9d;
}
</style>
